<?php





namespace app\admin\controller;



use app\admin\controller\ApiCommon;

use app\admin\model\Coupon as CouponModel;

use think\response\Json;

use Excel\Excel;

use app\common\traits\ActionRecordTrait;

use think\facade\Db;



/**

 * Class Coupon

 * @package app\shop\controller

 * @author Mr.Liu 优惠券模块

 * @create 2021-09-23 9:50

 */

class Coupon extends ApiCommon

{



    use ActionRecordTrait;

    /**

     * 用于判断权限

     * @permission 无限制

     * @allow 登录用户可访问

     * @author Mr.Li

     * @create 2021-05-26 16:20

     */

    public function initialize()

    {



        $action = [

            'permission' => ['exportcsv','import','delete_customer_coupon'],

            'allow' => [

                'synckingdeestock'

            ]

        ];

        event('CheckAuth', $action);

        $request = $this->request;

        $a       = strtolower($request->action());

        if (!in_array($a, $action['permission'])) {

            parent::initialize();

        }

    }



    /**

     * 优惠券列表

     * @return Json

     * @author Mr.Li

     * @create 2021-05-26 10:53

     */

    public function index(): Json

    {

        $CouponModel = new CouponModel();

        $data          = $CouponModel->getDataList($this->param);

        return resultArray(['data' => $data]);

    }



    /**

     * 优惠券详情

     * @return Json

     * @author Mr.Li

     * @create 2021-05-29 11:50

     */

    public function detail(): Json

    {

        $CouponModel = new CouponModel();

        $data          = $CouponModel->getDataDetail($this->param);

        if (!$data) {

            return resultArray(['error' => $CouponModel->getError()]);

        }

        return resultArray(['data' => $data]);

    }



    /**

     * 新增优惠券

     * @return Json

     * @author Mr.Li

     * @create 2021-05-26 11:26

     */

    public function create(): Json

    {



        $this->param['user'] = $this->userInfo;

        $CouponModel = new CouponModel();

        $data          = $CouponModel->addData($this->param);

        if (!$data) {

            return resultArray(['error' => $CouponModel->getError()]);

        }

        return resultArray(['data' => [],'error' => '创建成功']);

    }



    /**

     * 更新优惠券

     * @return Json

     * @author Mr.Li

     * @create 2021-05-26 11:33

     */

    public function update(): Json

    {

        $CouponModel = new CouponModel();

        $this->param['user'] = $this->userInfo;

        $data          = $CouponModel->saveData($this->param);

        if (!$data) {

            return resultArray(['error' => $CouponModel->getError()]);

        }

        return resultArray(['data' => [],'error' => '更新成功']);

    }



    /**

     * 删除优惠券

     * @return Json

     * @author Mr.Li

     * @create 2021-05-26 14:53

     */

    public function delete(): Json

    {

        $CouponModel = new CouponModel();

        $this->param['user'] = $this->userInfo;

        $data          = $CouponModel->deleteData($this->param);

        if (!$data) {

            return resultArray(['error' => $CouponModel->getError()]);

        }

        return resultArray(['data' => [],'error' => '删除成功']);

    }





    /**

     * 更新优惠券状态

     * @return Json

     * @author Mr.Li

     * @create 2021-06-03 11:11

     */

    public function updateStatus(): Json

    {

        $CouponModel = new CouponModel();

        $this->param['user'] = $this->userInfo;

        $data          = $CouponModel->updateStatus($this->param);

        if (!$data) {

            return resultArray(['error' => $CouponModel->getError()]);

        }

        return resultArray(['data' =>[],'error' => '更新成功']);

    }





    /**

     * 发放优惠券

     * @return Json

     * @author Mr.Liu

     * @create 2021-11-04 10:53

     */

    public function provide(): Json

    {

        $CouponModel = new CouponModel();

        $this->param['user'] = $this->userInfo;

        $data          = $CouponModel->couponProvide($this->param);

        if (!$data) {

            return resultArray(['error' => $CouponModel->getError()]);

        }

        return resultArray(['data' => [],'error' => '发放成功']);

    }







    /**

     * 查看优惠券发放详情

     * @return Json

     * @author Mr.Liu

     * @create 2021-11-05 14:23

     */

    public function provideCoupon(): Json

    {

        $CouponModel = new CouponModel();

        $data          = $CouponModel->getProvideDetail($this->param);

        return resultArray(['data' => $data]);

    }







    /**

     * 导出优惠券

     * @author Mr.Li

     * @create 2021-06-09 10:46

     */

    public function export()

    {



        $requestId = isset($this->request['id']) && $this->request['id'] ? $this->request['id'] : [];

        if($requestId){

            $idArr = is_array($requestId) ? $requestId : explode(',', $requestId);

        }else{

            $idArr = [];

        }

        $CouponModel = new CouponModel();

        $data          = $CouponModel->getDataList(['page' => 1,'limit' => 10000,'id' => $idArr]);

        if(empty($data['list'])){

            $data['list'] = [];

        }

        $callName = ['id' => '优惠券id','name' =>'优惠券名称','type' => '优惠券类型','rule' => '使用规则','denomination' => '面值','status_desc' => '优惠券状态','provide_status_desc' => '发放状态','create_time' => '创建时间','start_time' => '优惠券开始时间','end_time' => '优惠券结束时间'];

        $downUrl = exportExcelData('coupon',$callName,$data['list'],'xlsx',1);

        return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);

    }











    /**

     * 更新优惠券详情

     * @return Json

     * @author Mr.Li

     * @create 2021-06-22 14:23

     */

    public function updateContent(): Json

    {

        $CouponModel = new CouponModel();

        $this->param['user'] = $this->userInfo;

        $data          = $CouponModel->updateContent($this->param);

        if (!$data) {

            return resultArray(['error' => $CouponModel->getError()]);

        }

        return resultArray(['data' => [],'error' => '更新成功']);

    }





    /**

     * 同步金蝶库存

     * @return Json

     * @author Mr.Li

     * @create 2021-07-08 16:55

     */

    public function syncKingdeeStock()

    {

        $CouponModel = new CouponModel();

        $data      = $CouponModel->syncKingdeeStock();

        if (!$data) {

            return resultArray(['error' => '同步失败']);

        }

        return resultArray(['data' => [],'error' => '同步成功']);

    }





    /**

     * 出库记录

     * @author Mr.Li

     * @create 2021-07-24 13:44

     *

     */

    public function outboundRecord()

    {

        $data = (new \app\shop\model\OutHouse())->getDataList($this->param);

        return resultArray(['data' => $data,'error' => '获取成功']);

    }



    /**

     * 操作日志

     * @author Mr.Li

     * @create 2021-08-25 16:22

     */

    public function log()

    {

        $specId = $this->param['id'] ?? 0;

        $page = $this->param['page'] ?? 1;

        $limit = $this->param['limit'] ?? 20000;

        if(!$page){

            $page = 1;

        }

        $data = [];

        $total = 0;

        if($specId){

            $total = $this->getActionRecordTotal($specId,'shop','goods ');

            $data = $this->getActionRecordList($specId,'shop','goods ','',$page,$limit);

        }

        return resultArray(['data' => ['list' => $data,'dataCount' => $total ]]);



    }





    /**

     * 导入优惠券

     * @param CouponModel $CouponModel

     * @return Json

     * @author Mr.Li

     * @create 2021-09-07 15:49

     */

    public function import(CouponModel $CouponModel)

    {

        if (empty($_FILES['file'])) {

            return resultArray(['error' => '文件不存在！']);

        }

        $tmp_name = $_FILES['file']['tmp_name'];

        if (empty($tmp_name) || !file_exists($tmp_name)) {

            return resultArray(['error' => '文件不存在！']);

        }

        $importData = readExcelData($tmp_name);

        $res = $CouponModel->import($importData);

        if (!$res) {

            return resultArray(['error' => $CouponModel->getError()]);

        }

        return resultArray(['data' => $importData, 'error' => '导入成功']);



    }



    /**

     *

     * @return string

     * @author lilongfei

     * @date 2021-09-08 17:24

     */

    public function exportCsv()

    {

        return '';

        set_time_limit(0);

        ini_set('memory_limit',-1);

        $requestId = isset($this->request['id']) && $this->request['id'] ? $this->request['id'] : [28];

        if($requestId){

            $idArr = is_array($requestId) ? $requestId : explode(',', $requestId);

        }else{

            $idArr = [];

        }

        $CouponModel = new CouponModel();

        $data          = $CouponModel->getDataList(['page' => 1,'limit' => 10000,'id' => $idArr]);

        if(empty($data['list'])){

            $data['list'] = [];

        }

       $exportData = [];



        if(!empty($data['list'])){

            $data['list'] = array_pad($data['list'],1000000,$data['list'][0]);

            foreach($data['list'] as $v){

                $itemd = [];

                foreach($v as $k => $item){

                    if($k == 'spec_list'){

                        continue;

                    }

                    $itemd[] = $item;



                }

                $exportData[] = $itemd;

            }

        }

        $headLine = ['优惠券id','优惠券名称','描述','状态','价格','供应商','金蝶编码','创建时间','更新时间','图片','金蝶库存单位','优惠券分类','销售单位','规格','创建人'];

        csv_export( $exportData,$headLine,'goods.csv',0);

    }

    // 一件发放会员券（创建+发放）
    public function oneProvide(){

        $CouponModel = new CouponModel();

        $this->param['user'] = $this->userInfo;

        $data = $CouponModel->oneProvide($this->param);

        if (!$data) {

            return resultArray(['error' => $CouponModel->getError()]);

        }

        return resultArray(['data' => $data,'error' => '发放成功']);

    }

    public function delete_customer_coupon()
    {
        $couponids = [109];

        $where = [];

        array_push($where,['coupon_id','in',$couponids]);

        Db::name('coupon_provide_customer')->where($where)->delete();
        
    }


}

